<template>
	<section>
		<!--工具条-->
		<el-col :span="24" class="toolbar" style="padding-bottom: 0;">
			<el-form :inline="true" :model="filters">
				<el-form-item>
					<el-input v-model="filters.name" placeholder="部门名称"></el-input>
				</el-form-item>
				<el-form-item>
					<el-button type="primary" v-on:click="search">查询</el-button>
				</el-form-item>
				<el-form-item>
					<el-button type="primary" @click="handleAdd">新增</el-button>
				</el-form-item>
			</el-form>
		</el-col>

		<!--列表-->
		<el-table :data="pageInfo.rows"
              highlight-current-row
              v-loading="listLoading"
              element-loading-spinner="el-icon-loading"
              element-loading-text="拼命加载中"
              @selection-change="selsChange"
              :cell-style="cellStyle">
			<el-table-column type="selection" width="55">
			</el-table-column>
			<el-table-column type="index" width="60">
			</el-table-column>
			<el-table-column prop="name" label="部门名称" width="120" sortable>
			</el-table-column>
			<el-table-column prop="intro" label="部门介绍" width="200" :show-overflow-tooltip="true" sortable>
			</el-table-column>
			<el-table-column prop="createTime" label="创建时间" :show-overflow-tooltip="true" width="100" sortable>
			</el-table-column>
			<el-table-column prop="updateTime" label="修改时间" :show-overflow-tooltip="true" width="120" sortable>
			</el-table-column>
			<el-table-column prop="manager.username" label="部门经理" min-width="120" sortable>
			</el-table-column>
      <el-table-column prop="parent.name" label="父部门" min-width="120" sortable>
      </el-table-column>
      <el-table-column prop="path" label="路径" min-width="180" sortable>
      </el-table-column>
      <el-table-column prop="state" label="状态" min-width="180" sortable  :formatter="formatState">
        <template slot-scope="scope">
          状态:
          <el-switch
              v-model="scope.row.state"
              :active-value="1"
              :inactive-value="0"
              @change="switchReceiveStatus($event,scope.row)"
          />
        </template>
      </el-table-column>
			<el-table-column label="操作" width="150">
				<template slot-scope="scope">
					<el-button size="small" @click="handleEdit(scope.$index, scope.row)">编辑</el-button>
					<el-button type="danger" size="small" @click="handleDel(scope.$index, scope.row)">删除</el-button>
				</template>
			</el-table-column>
		</el-table>

		<!--工具条-->
		<el-col :span="24" class="toolbar">
			<el-button type="danger" @click="batchRemove" :disabled="this.sels.length===0">批量删除</el-button>
			<el-pagination layout="total,sizes,prev, pager, next"
                     @size-change="handleSizeChange"
                     @current-change="handleCurrentChange"
                     :current-page="query.currentPage"
                     :page-sizes="[5, 10, 50, 100]"
                     :page-size="10"
                     :total="pageInfo.total"
                     style="float:right;">
			</el-pagination>
		</el-col>

		<!--新增界面-->
		<el-dialog title="保存" :visible.sync="addFormVisible" :close-on-click-modal="false">
			<el-form :model="addForm" label-width="80px" :rules="addFormRules" ref="addForm">
        <el-row :gutter="10">
          <el-col :span="12">
            <el-form-item label="部门名称" prop="name">
              <el-input v-model="addForm.name" auto-complete="off"></el-input>
            </el-form-item>
          </el-col>
<!--          <el-col :span="12">
            <el-form-item label="路径" prop="path">
              <el-input v-model="addForm.path" auto-complete="off"></el-input>
            </el-form-item>
          </el-col>-->
        </el-row>
        <el-row>
          <el-col :span="24">
              <el-form-item label="部门介绍" prop="intro">
                <el-input type="textarea"
                          v-model="addForm.intro"
                          placeholder="请输入内容"
                          maxlength="50"
                          show-word-limit
                          auto-complete="off"></el-input>
              </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="部门经理" prop="manager">
              <el-select v-model="addForm.manager.id" clearable placeholder="请选择">
                <el-option
                    v-for="item in manager"
                    :key="item.id"
                    :label="item.username"
                    :value="item.id">
                  <span style="float: left">{{ item.username }}</span>
                  <span style="float: right; color: #8492a6; font-size: 13px">{{ item.email }}</span>
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="父部门" prop="parent">
              <el-cascader
                  v-model="path"
                  placeholder="搜索"
                  :options="parent"
                  :props="{checkStrictly: true,value:'id',label:'name',children:'children'}"
                  filterable
                  clearable>
              </el-cascader>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="状态" prop="state">
              <el-radio-group v-model="addForm.state">
                <el-radio class="radio" :label="1">启用</el-radio>
                <el-radio class="radio" :label="0">禁用</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>
			</el-form>
			<div slot="footer" class="dialog-footer">
				<el-button @click.native="addFormVisible = false">取消</el-button>
				<el-button type="primary" @click.native="addSubmit" :loading="addLoading">提交</el-button>
			</div>
		</el-dialog>
	</section>
</template>

<script>
	export default {
		data() {
			return {
        value:true,
        path:null,
        color:null,
				filters: {
					name: ''
				},
        department:{},
        pageInfo:{
          rows: [],
          total: 0,
        },
				listLoading: false,
        //列表选中列
				sels: [],
        // 父部门
        parent:[],
        // 部门经理
        manager:{
          username:"",
          id:"",
          email:""
        },
				addFormVisible: false,//新增界面是否显示
				addLoading: false,
				addFormRules: {
					name: [
						{ required: true, message: '请输入部门名称', trigger: 'blur' }
					],
          state: [
            { required: true, message: '请选择是否启用', trigger: 'blur'},
          ]
				},
				//新增界面数据
				addForm: {
          id:'',
          name:'',
          intro:'',
          manager:{
            id:'',
          },
          parent:{
            id:''
          },
				},
        // 查询体
        query:{
          currentPage:1,
          pageSize:10,
          keyword:null
        },
			}
		},
		methods: {
      switchReceiveStatus(event,row){
        this.$http.put("/department/save",row).then(()=>{
        }).catch(()=>{
          this.$message({type:"error",message:"网络错误！"});
        })
      },
      handleForbidden(){
        //TODO
      },
      // 禁用启用样式
      cellStyle:function ({row, column}){
        let cellStyle;
        switch (row.state){
          case 0:
            cellStyle='color:red';
            break;
          case 1:
            cellStyle="color:green";
            break;
          default:
            cellStyle="";
        }
        if(column.label==='状态'||column.label==="状态"){
          return cellStyle;
        }
      },
      // 禁用启用格式转换
      formatState: function (row) {
        return row.state === 1 ? '启用' : row.state === 0 ? '禁用' : '未知';
      },
      // 高级查询
      search(){
        this.query.currentPage = 1;
        this.getDepartments();
      },
      // 单页大小转换
      handleSizeChange(val){
        this.query.pageSize=val;
        this.query.currentPage=1;
        this.getDepartments();
      },
      // 页面跳转
			handleCurrentChange(val) {
        this.query.currentPage = val;
				this.page = val;
				this.getDepartments();
			},
			// 获取部门分页列表
			getDepartments() {
        this.query.keyword = this.filters.name;
        this.$http.post("/department",this.query).then(result=>{
          result = result.data;
          if(result.success){
            this.pageInfo = result.object;
          } else {
            this.$message({type:"error",message:result.message})
          }
        }).catch(() => {
          this.$message({type:"error",message:"网络错误"})
        })
			},
      // 获取所有员工
      getAllEmployee(){
        this.$http.post("/employee/getAll").then(result=>{
          result = result.data;
          if(result.success){
            this.manager = result.object;
          } else {
            this.$message({type:"error",message:result.message})
          }
        }).catch(() => {
          this.$message({type:"error",message:"网络错误"})
        })
      },
			// 部门删除
			handleDel: function (index, row) {
				this.$confirm('确认删除该记录吗?', '提示', {
					type: 'warning'
				}).then(() => {
					this.listLoading = true;
					this.$http.delete("/department/delete/"+row.id).then((result) => {
						this.listLoading = false;
            this.query.currentPage=1;
						this.getDepartments();
					});
				}).catch(() => {
          this.$message({type:"warning",message:"已取消删除!"})
				});
			},
			// 显示编辑界面
			handleEdit: function (index, row) {
        // 查询父部门和部门经理
        this.getSelect();
        // 回显父部门
        this.parent.push({
          name:"",
          id:""
        });
        let paths = row.path.split("/");
        if(paths[paths.length-2]==""){
          this.path=null;
        } else {
          this.path = Number(paths[paths.length-2]);
        }
        console.log(this.path)
        // 展示编辑框
				this.addFormVisible = true;
        this.$http.get("/department/getById/"+row.id).then(result=>{
          result = result.data;
          if(result.success){
            this.addForm = result.object;
            if(!row.parent){
              this.addForm.parent={
                id:'',
                name:""
              }
            }
            if(!row.manager){
              this.addForm.manager={
                id:'',
                username:""
              }
            }
          } else {
            this.$message({type:"error",message:result.message})
          }
        }).catch(() => {
          this.$message({type:"error",message:"网络错误"});
        })
			},
			// 显示新增界面
			handleAdd: function () {
        this.clear();
        this.getSelect();
				this.addFormVisible = true;
			},
			// 新增/修改
			addSubmit: function () {
				this.$refs.addForm.validate((valid) => {
					if (valid) {
						this.$confirm('确认提交吗？', '提示', {}).then(() => {
							this.addLoading = true;
              console.log(this.path)
              // 对父部门进行处理 如果路径不为空值，空数组。
              if(this.path!==null&&this.path!==""&&this.path.length!==0){
                // 父部门的id
                this.addForm.parent.id=this.path[this.path.length-1];
                // 如果为空数组 截取为undefined 重新取值
                if(!this.addForm.parent.id){
                  this.addForm.parent.id = this.path;
                }
              } else{
                // 修改为父部门
                this.addForm.parent.id=null;
              }
              console.log(this.addForm.parent.id)
              this.addForm.business_id = "BN001"
							this.$http.put("/department/save",
                  this.addForm,
                  {
                    headers:{
                      operation_type:"BN001",
                      business_id:"BNP001"
                    }
                  }).then(() => {
								this.addLoading = false;
								this.$refs['addForm'].resetFields();
								this.addFormVisible = false;
								this.getDepartments();
							});
						});
					}
				});
			},
      // 批量删除选择
			selsChange: function (sels) {
				this.sels = sels;
			},
			// 部门批量删除
			batchRemove: function () {
				let ids = this.sels.map(item => item.id);
				this.$confirm('确认删除选中记录吗？', '提示', {
					type: 'warning'
				}).then(() => {
					this.listLoading = true;
					this.$http.patch("/department/deleteBatch",ids).then(() => {
            this.listLoading = false;
            this.query.currentPage=1;
						this.getDepartments();
					}).catch(() => {
            this.$message({message: '网络错误!',type: 'error'});
          })
				}).catch(() => {
          this.$message({message: '已取消删除!',type: 'warning'});
				});
			},
      // 编辑页面负责人和部门下拉框
      getSelect(){
        this.getTree();
        this.getAllEmployee();
      },
      // 获取部门级联选择
      getTree(){
        this.$http.get("/department/tree").then(result=>{
          result = result.data;
          if(result.success){
            this.parent = result.object;
          } else {
            this.$message({type:"error",message:result.message})
          }
        }).catch(() => {
          this.$message({type:"error",message:"网络错误!"})
        })
      },
      clear(){
        this.path = null;
        this.addForm ={
          id:'',
          name:'',
          intro:'',
          manager:{
            id:'',
          },
          parent:{
            id:''
          },
          path:"",
        };
      },
		},
		mounted() {
      this.getDepartments();
    }
	}

</script>

<style scoped>

</style>